package com.why.zing.alipay.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.why.zing.alipay.builder.AbstractRequestBuilder;
import lombok.extern.slf4j.Slf4j;

/**
 * 支付抽象类
 *
 * @author 睁眼看世界
 * @date 2020年1月10日
 */
@Slf4j
public abstract class AbstractAlipayService {

    /**
     * 验证bizContent对象
     */
    protected void validateBuilder(AbstractRequestBuilder builder) {
        if (builder == null) {
            throw new NullPointerException("builder should not be NULL!");
        }

        if (!builder.validate()) {
            throw new IllegalStateException("builder validate failed! " + builder.toString());
        }
    }

    /**
     * 调用AlipayClient的execute方法，进行远程调用
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected AlipayResponse getResponse(AlipayClient client, AlipayRequest request) {
        try {
            AlipayResponse response = client.execute(request);
            if (response != null) {
                log.info(response.getBody());
            }
            return response;
        } catch (AlipayApiException e) {
            log.error("调用AlipayClient的execute方法异常", e);
            return null;
        }
    }
}
